package com.superhelper.app.controller.base;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.superhelper.app.common.CommonHelper;
import com.superhelper.app.common.Consts;
import com.superhelper.app.domain.Admin;
import com.superhelper.app.domain.Resp;
import com.superhelper.app.service.AdminService;
import com.superhelper.app.service.JHSmsHandler;
import com.superhelper.app.service.ShopService;
import com.superhelper.app.utils.DateEditor;
import com.superhelper.app.utils.NumberEditor;
import com.superhelper.common.exception.ServiceException;
import com.superhelper.common.service.RedisService;
import com.superhelper.common.utils.RSAUtils;
import com.superhelper.common.utils.ThreadPool;

/**
 * 定义共用方法属性
 * 
 *
 */
public class AbstractController {

    protected Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired(required = true)
    protected AdminService adminService;

    @Autowired(required = true)
    protected ShopService shopService;

    @Autowired
    protected ThreadPool threadPool;

    @Autowired
    protected RedisService redisService;

    @Autowired
    protected JHSmsHandler smsHandler;

    @Value("${online}")
    protected Boolean online;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new DateEditor());
        binder.registerCustomEditor(int.class, new NumberEditor());
    }

    /**
     * 验证码校验
     * 
     * @param type
     *            注册类型
     * @param code
     *            验证码
     * @param phone
     *            手机号码
     * @return
     */
    protected boolean verifyCode(String type, String code, String phone) {
        String rightCode = redisService.getString(phone + "_" + type);
        if (rightCode == null) {
            return false;
        }
        return StringUtils.equalsIgnoreCase(code, rightCode);
    }

    /**
     * 对异常情况的处理，返回异常信息
     * 
     * @param t
     * @return
     */
    protected Resp error(Throwable t) {
        ServiceException ge = null;
        if (t instanceof ServiceException) {
            ge = (ServiceException) t;
        } else {
            ge = new ServiceException();
            ge.setCode(Consts.Code.INTERNAL_ERROR);
            ge.setMsg("error");
        }
        Resp resp = new Resp(ge.getCode(), ge.getMsg());
        return resp;
    }

    /**
     * 返回成功的响应
     * 
     * @return
     */
    protected <T> Resp success() {
        Resp resp = new Resp(Consts.Code.SUCCESS, null, null);
        return resp;
    }

    /**
     * 返回失败的响应
     * 
     * @return
     */
    protected <T> Resp fail() {
        Resp resp = new Resp(Consts.Code.FAIL, null, null);
        return resp;
    }

    /**
     * 返回成功的响应
     * 
     * @param data
     * @return
     */
    protected <T> Resp success(T data) {
        Resp resp = new Resp(Consts.Code.SUCCESS, null, data);
        return resp;
    }

    /**
     * 返回失败的响应
     * 
     * @return
     */
    protected <T> Resp fail(String msg) {
        Resp resp = new Resp(Consts.Code.FAIL, msg, null);
        return resp;
    }

    /**
     * 返回成功的响应
     * 
     * @param data
     * @param msg
     * @return
     */
    protected <T> Resp success(T data, String msg) {
        Resp resp = new Resp(Consts.Code.SUCCESS, msg, data);
        return resp;
    }

    protected <T> Resp reqError() {
        Resp resp = new Resp(Consts.Code.DATA_ERROR, null, null);
        return resp;
    }

    /* =============================返回指定状态码的信息=========================== */

    /**
     * 返回指定状态码的信息
     * 
     * @return
     */
    protected <T> Resp resp(int code) {
        Resp resp = new Resp(code, null, null);
        return resp;
    }

    /**
     * 返回指定状态码的信息
     * 
     * @return
     */
    protected <T> Resp resp(int dataError, String string) {
        Resp resp = new Resp(dataError, string, null);
        return resp;
    }

    /**
     * 返回指定状态码的信息
     * 
     * @return
     */
    protected <T> Resp resp(int code, String msg, Object data) {
        Resp resp = new Resp(code, msg, data);
        return resp;
    }

    protected String generateToken(Long userId, String imid) {

        String tokenKey = Consts.Cache.USER_TOKEN_KEY + userId;
        String token = redisService.getString(tokenKey);
        if (StringUtils.isBlank(token)) {
            token = RSAUtils.encrypt(userId + ";" + imid + ";" + System.currentTimeMillis(), online);
            redisService.setString(tokenKey, token, Consts.DAY_AGE);
        }
        return token;
    }

    protected String flushToken(Long userId, String imid) {
        String tokenKey = Consts.Cache.USER_TOKEN_KEY + userId;
        String tmpkey = "tmp" + tokenKey;
        long tmp = redisService.setStringIfNotExists(tmpkey, imid);
        redisService.expire(tmpkey, 60);
        if (tmp > 0) {
            String token = RSAUtils.encrypt(userId + ";" + imid + ";" + System.currentTimeMillis(), online);
            redisService.setString(tokenKey, token, Consts.DAY_AGE);
            return token;
        } else {
            String token = redisService.getString(tokenKey);
            return token;
        }
    }

    protected boolean isExpireAt(Long userId) {
        Admin user = adminService.getAdminById(userId);
        long time = CommonHelper.getDateFormat("yyyy-MM-dd", new Date()).getTime();
        long expireAt = CommonHelper.getDateFormat("yyyy-MM-dd", user.getExpireAt()).getTime();
        if ("com.superhelper.superaide".equals(user.getPackageName()) && (time - expireAt > 0)) {
            log.info("expireAt:{}", user.getExpireAt());
            return true;
        }
        return false;
    }

}
